package com.hyny.framework.platform.system.utils;


import com.hyny.framework.platform.system.exception.CommonException;
import com.hyny.framework.platform.system.entity.vo.LoginVO;
import com.hyny.framework.platform.system.utils.enums.ResultEnum;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

/**
 * 获取登录用户信息的帮助类
 */
@Component
public class SecurityUtil {

    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 获取用户信息
     **/
    public static LoginVO getLoginUser() {
        try {
            return (LoginVO) getAuthentication().getPrincipal();
        } catch (Exception e) {
            throw new CommonException(ResultEnum.ERROR.getCode(), "获取用户信息异常");
        }
    }

    /**
     * 获取用户编号
     **/
    public static Long getUserId() {
        try {
            return getLoginUser().getUser().getId();
        } catch (Exception e) {
            throw new CommonException(ResultEnum.ERROR.getCode(), "获取用户编号异常");
        }
    }

    /**
     * 获取用户账户
     **/
    public static String getUsername() {
        try {
            return getLoginUser().getUsername();
        } catch (Exception e) {
            throw new CommonException(ResultEnum.ERROR.getCode(), "获取用户账户异常");
        }
    }


}
